/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at

 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.bytedance.scene;

import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.ability.fraction.FractionAbility;
import ohos.aafwk.ability.fraction.FractionManager;
import ohos.global.systemres.ResourceTable;

import java.util.Optional;

/**
 * Created by JiangQi on 9/12/18.
 */
public class ScopeHolderFragment extends Fraction implements Scope.RootScopeFactory {
    private static final String TAG = "ScopeHolderFragment";
    private final Scope mRootScope = Scope.DEFAULT_ROOT_SCOPE_FACTORY.getRootScope();

    private static ScopeHolderFragment newInstance() {
        return new ScopeHolderFragment();
    }

    /**
     * 安装
     *
     * @param idRs
     * @param ability
     * @param tag
     * @param forceCreate
     * @param immediate
     * @return ScopeHolderFragment
     */
    public static ScopeHolderFragment install(int idRs,FractionAbility ability, String tag,
                                              boolean forceCreate, boolean immediate) {
        String fragmentTag = tag + "_" + TAG;
        FractionManager fragmentManager = ability.getFractionManager();

        Optional<Fraction> fractionByTag=fragmentManager.getFractionByTag(fragmentTag);
        ScopeHolderFragment holderFragment=null;

        if(fractionByTag.isPresent()){
            holderFragment = (ScopeHolderFragment) fractionByTag.get();
            if (forceCreate) {
                fragmentManager.startFractionScheduler().remove(holderFragment).submit();
                holderFragment = null;
            }
        }
        if (holderFragment == null) {
            holderFragment = ScopeHolderFragment.newInstance();
            fragmentManager.startFractionScheduler().add(idRs,holderFragment,fragmentTag).submit();
        }

        return holderFragment;
    }

    @Override
    public Scope getRootScope() {
        return mRootScope;
    }
}
